/*
 * Created on 29/04/2008
 */
package com.apbetioli.mapr.place.control.flickr;

import com.aetrion.flickr.Flickr;
import com.aetrion.flickr.FlickrException;
import com.aetrion.flickr.photos.GeoData;
import com.aetrion.flickr.photos.Photo;
import com.aetrion.flickr.photos.PhotoList;
import com.aetrion.flickr.photos.geo.GeoInterface;
import com.aetrion.flickr.photosets.PhotosetsInterface;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xml.sax.SAXException;

/**
 * Credits to  http://toys.lerdorf.com/archives/34-Flickr-API-Fun.html
 *         and FlickrJ Api Documentation
 * 
 * Get all the photos from an user:
 *  
 * PeopleInterface people = flickr.getPeopleInterface();
 * PhotoList photos = people.getPublicPhotos(user_id, 1000, 1);
 * 
 * 
 * @author Alexandre Parra Betioli
 */
public class FlickrPhotoLocator {

    private String apiKey;
    private String userId;
    private String photosetId;
    private double latitude;
    private double longitude;
    private static final String EXT = "jpg";

    public FlickrPhotoLocator( final String apiKey, final String userId, final String photosetId) {
        this.apiKey = apiKey;
        this.userId = userId;
        this.photosetId = photosetId;
    }

    public String getPhotosetUrl() {
        return "http://www.flickr.com/" + userId + "/sets/" + photosetId + "/";
    }
    
    public String getPhotoUrl( final Photo p ) {
        return "http://www.flickr.com/" + userId + "/" + p.getId() + "/in/set-" + photosetId + "/";
    }

    public String getSmallImageUrl( final double latitude, final double longitude) {
        try {
            this.latitude = latitude;
            this.longitude = longitude;

            Photo p = this.findPhoto();

            return getPhotoWithLink(p, ImageSize.SMALL, EXT);

        } catch (IOException ex) {
            Logger.getLogger(FlickrPhotoLocator.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(FlickrPhotoLocator.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FlickrException ex) {
            Logger.getLogger(FlickrPhotoLocator.class.getName()).log(Level.WARNING, null, ex);
        }

        return null;
    }

    public String getMediumImageUrl( final double latitude, final double longitude) {
        try {
            this.latitude = latitude;
            this.longitude = longitude;

            Photo p = this.findPhoto();

            return getPhotoWithLink(p, ImageSize.MEDIUM, EXT);

        } catch (IOException ex) {
            Logger.getLogger(FlickrPhotoLocator.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(FlickrPhotoLocator.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FlickrException ex) {
            Logger.getLogger(FlickrPhotoLocator.class.getName()).log(Level.WARNING, null, ex);
        }

        return null;
    }

    public String getBigImageUrl( final double latitude, final double longitude) {
        try {
            this.latitude = latitude;
            this.longitude = longitude;

            Photo p = this.findPhoto();

            return getPhotoWithLink(p, ImageSize.BIG, EXT);

        } catch (IOException ex) {
            Logger.getLogger(FlickrPhotoLocator.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(FlickrPhotoLocator.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FlickrException ex) {
            Logger.getLogger(FlickrPhotoLocator.class.getName()).log(Level.WARNING, null, ex);
        }

        return null;
    }

    private String getStaticPhotoURL( final Photo p, final ImageSize size, final String ext) {
        return "http://static.flickr.com/" + p.getServer() + "/" + p.getId() + "_" + p.getSecret() + "_" + size + "." + ext;
    }
    
    private String getPhotoWithLink( final Photo p, final ImageSize size, final String ext) {
        if( p == null )
            return "";
       
        return "<a href=\"" + getPhotoUrl(p) + "\"><img src=\"" + getStaticPhotoURL(p, size, ext) + "\"></img></a>";
    }

    private Photo findPhoto() throws IOException, SAXException, FlickrException {

        Flickr flickr = new Flickr(apiKey);

        Photo chosen = null;

        //Gets a list of photosets from the user (keys owner)

        PhotosetsInterface pi = flickr.getPhotosetsInterface();


        PhotoList photos = pi.getPhotos(photosetId, 500, 0);

        for (Object o : photos) {
            Photo p = (Photo) o;

            GeoData gd = null;
            
            try {
                GeoInterface gi = flickr.getPhotosInterface().getGeoInterface();
                gd = gi.getLocation(p.getId());
            } catch( FlickrException e ) {
                /* If the photo has no location info, it generates the exception.
                 * At this point, we just continue verifying the other photos */
                continue;
            }

            if (gd == null) {
                continue;
            }

            if (isNear(gd.getLatitude(), gd.getLongitude())) {

                chosen = p;
                break;
            }
        }

        return chosen;

    }

    private boolean isNear( final double latitude, final double longitude) {
        return (Math.abs(this.latitude - latitude) <= 0.01) &&
                (Math.abs(this.longitude - longitude) <= 0.01);

    }
}


